package com.wf.wxsign.controller;

import com.alibaba.fastjson.JSON;
import com.wf.wxsign.common.JsonResult;
import com.wf.wxsign.common.utils.*;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.io.IOException;
import java.util.Date;

/**
 * Created by wangfan on 2018-12-13 下午 4:47.
 */
@CrossOrigin(origins = "*", maxAge = 3600)
@RequestMapping("/api")
@RestController
public class ApiController {

    // 获取微信JS-SDK签名
    @RequestMapping("/getJSSDKSignature")
    public JsonResult getJSSDKSignature(String url) {


        String access_token = "";
        AccessTokenModel accessTokenModel = new AccessTokenModel() ;
        String expiresTime = "";
        try {
            File file = new File(System.getProperty("user.dir") + "/accessToken.conf");
            if(!file.exists()){
                file.createNewFile();
            }
            String string = FileUtils.readFileToString(new File(System.getProperty("user.dir")+"/accessToken.conf"),"utf-8");
            accessTokenModel = JSONUtil.parseObject(string, AccessTokenModel.class);

            if(accessTokenModel!=null){
                access_token = accessTokenModel.getAccessToke();
                expiresTime = accessTokenModel.getExpiresTime();
            }

        }catch (Exception e){
            e.printStackTrace();
            System.out.println("报错了");
        }
        if(access_token == null || access_token.equals("")){
            String tokenJson = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Constants.APPID + "&secret=" + Constants.SECRET, null);
            access_token = JSONUtil.getString(tokenJson, "access_token");  // access_token
            long time = new Date().getTime();
            time = time+7100;
            if(accessTokenModel == null){
                accessTokenModel = new AccessTokenModel() ;
            }
            File file = new File(System.getProperty("user.dir") + "/accessToken.conf");
            accessTokenModel.setAccessToke(access_token);
            accessTokenModel.setExpiresTime(time+"");
            String temp = JSON.toJSONString(accessTokenModel);
            try {
                FileUtils.writeStringToFile(file,temp);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }else{

            Long currentMilll = new Date().getTime();
            long parseLong = Long.parseLong(expiresTime);
            if(parseLong>=currentMilll){
                String tokenJson = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + Constants.APPID + "&secret=" + Constants.SECRET, null);
                access_token = JSONUtil.getString(tokenJson, "access_token");  // access_token
                long time = new Date().getTime();
                time = time+7100;
                if(accessTokenModel == null){
                    accessTokenModel = new AccessTokenModel() ;
                }
                File file = new File(System.getProperty("user.dir") + "/accessToken.conf");
                accessTokenModel.setAccessToke(access_token);
                accessTokenModel.setExpiresTime(time+"");
                String temp = JSON.toJSONString(accessTokenModel);
                try {
                    FileUtils.writeStringToFile(file,temp);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        String ticketJson = HttpUtil.get("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=" + access_token + "&type=jsapi", null);
        String ticket = JSONUtil.getString(ticketJson, "ticket");  // ticket
        String noncestr = UUIDUtil.randomUUID8();  // 随机字符串
        long timestamp = new Date().getTime();  // 时间戳
        String str = "jsapi_ticket=" + ticket;
        str += "&noncestr=" + noncestr;
        str += "&timestamp=" + timestamp;
        str += "&url=" + url;
        String signature = DigestUtils.sha1Hex(str);
        return JsonResult.ok().put("timestamp", timestamp).put("nonceStr", noncestr).put("signature", signature).put("appId",Constants.APPID);
    }

    /**
     * access_token请求接口：
     * https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=xxx&secret=xxx
     * 返回示例：
     * {"access_token":"xxxxxx","expires_in":7200}
     *
     * ticket请求接口：
     * https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=xxx&type=jsapi
     * 返回示例：
     * {"errcode":0,"errmsg":"ok","ticket":"xxxxx","expires_in":7200}
     */
}
